/*
 * ChoixCatalogue.java
 *
 * Created on 26 mai 2011, 15:35:14
 */

package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import main.model.CatalogueContact;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author silberfab
 */
public class ChoixCatalogue extends javax.swing.JDialog {

    private DefaultListModel model;
    private DownloadOPDSView view;
    private final String fichierConf = "./DownOpds.conf";
    private ArrayList<CatalogueContact> oCatalogues;

    /** Creates new form ChoixCatalogue */
    public ChoixCatalogue(java.awt.Frame parent, boolean modal, DownloadOPDSView view) {
        super(parent, modal);
        initComponents();
        this.view = view;

        //On initialise la liste des catalogue
        oCatalogues = new ArrayList<CatalogueContact>();
        initModelList();
        initListeCatalogues();
    }

    private void ajoutContact(CatalogueContact contact){
        SAXBuilder builder = new SAXBuilder();
        File conf = new File(fichierConf);

        try{
            Document document = (Document) builder.build(conf);
            Element rootNode = document.getRootElement();
            
            //Récupération du noeud de type Catalogues
            Element catalogueListNode = rootNode.getChild("catalogues");
            catalogueListNode.addContent(
                    new Element("catalogue").setAttribute("nom", contact.getNom()).setText(contact.getAdresse()));

            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, new FileWriter(fichierConf));
        }
        catch(IOException io){
                System.out.println(io.getMessage());
        }
        catch(JDOMException jdomex){
                System.out.println(jdomex.getMessage());
        }
    }

    private void supprimeContact(int index){
        SAXBuilder builder = new SAXBuilder();
        File conf = new File(fichierConf);

        try{
            Document document = (Document) builder.build(conf);
            Element rootNode = document.getRootElement();

            //Récupération du noeud de type Catalogues
            Element catalogueListNode = rootNode.getChild("catalogues");

            //Récupération de tous les catalogues
            List catalogueList = catalogueListNode.getChildren("catalogue");
            catalogueList.remove(index);
            
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, new FileWriter(fichierConf));
        }
        catch(IOException io){
                System.out.println(io.getMessage());
        }
        catch(JDOMException jdomex){
                System.out.println(jdomex.getMessage());
        }
    }

    /**
     * Parse le fichier xml de configuration pour en extraire la liste des catalogues
     */
    private void initListeCatalogues(){
        
        SAXBuilder builder = new SAXBuilder();
        File conf = new File(fichierConf);

        try{
            Document document = (Document) builder.build(conf);
            Element rootNode = document.getRootElement();
            //Récupération du noeud de type Catalogues
            Element catalogueListNode = rootNode.getChild("catalogues");

            //Récupération de tous les catalogues
            List catalogueList = catalogueListNode.getChildren("catalogue");

            //Chaque noeud représente un catalogue
            for (int i=0; i< catalogueList.size(); i++)
            {
                //Nous récupérons un noeud catalogue
                Element catalogueNode = (Element) catalogueList.get(i);
                String nom = catalogueNode.getAttributeValue("nom");
                String adresse = catalogueNode.getText();
                CatalogueContact contact = new CatalogueContact(nom, adresse);
                model.addElement(contact.getNom());
                oCatalogues.add(contact);
            }

            this.catalogueLst.setModel(model);
        }
        catch(IOException io){
                System.out.println(io.getMessage());
        }
        catch(JDOMException jdomex){
                System.out.println(jdomex.getMessage());
        }
    }

    private void initModelList(){
        model = new DefaultListModel();

        btAjouter.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String nom = ajoutNom.getText();
                String adresse = ajoutAdresse.getText();
                CatalogueContact contact = new CatalogueContact(nom, adresse);
                model.addElement(contact.getNom());
                oCatalogues.add(contact);

                //On ajoute dans le fichier conf
                ajoutContact(contact);
            }
        });

        btSupprimer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (model.getSize() > 0){
                    int i = catalogueLst.getSelectedIndex();
                    model.removeElementAt(i);

                    //On supprieme dans le fichier conf
                    supprimeContact(i);
                }
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        catalogueLst = new javax.swing.JList();
        btSelectionner = new javax.swing.JButton();
        ajoutNom = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        ajoutAdresse = new javax.swing.JTextField();
        btAjouter = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        btSupprimer = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Organiser sa collection de catalogue");

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        catalogueLst.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        catalogueLst.setName("catalogueLst"); // NOI18N
        jScrollPane1.setViewportView(catalogueLst);

        btSelectionner.setText("Sélectionner");
        btSelectionner.setName("btSelectionner"); // NOI18N
        btSelectionner.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btSelectionnerMouseClicked(evt);
            }
        });

        ajoutNom.setName("ajoutNom"); // NOI18N

        jLabel1.setText("Nom");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("Adresse");
        jLabel2.setName("jLabel2"); // NOI18N

        ajoutAdresse.setName("ajoutAdresse"); // NOI18N

        btAjouter.setText("Ajouter");
        btAjouter.setName("btAjouter"); // NOI18N

        jLabel3.setText("Sélectionnez l'adresse du catalogue OPDS :");
        jLabel3.setName("jLabel3"); // NOI18N

        btSupprimer.setText("Supprimer");
        btSupprimer.setName("btSupprimer"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btSupprimer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btSelectionner))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ajoutNom, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ajoutAdresse, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
                    .addComponent(btAjouter, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btSelectionner)
                            .addComponent(btSupprimer))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                        .addComponent(ajoutAdresse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(ajoutNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)))
                .addGap(11, 11, 11)
                .addComponent(btAjouter)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSelectionnerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btSelectionnerMouseClicked
        int i = catalogueLst.getSelectedIndex();
        this.view.adrDropBox.setText(oCatalogues.get(i).getAdresse());
        dispose();
    }//GEN-LAST:event_btSelectionnerMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ajoutAdresse;
    private javax.swing.JTextField ajoutNom;
    private javax.swing.JButton btAjouter;
    private javax.swing.JButton btSelectionner;
    private javax.swing.JButton btSupprimer;
    private javax.swing.JList catalogueLst;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
